package com.dev.module_zqc_sleep.broadcast

import android.app.AlarmManager
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.media.AudioAttributes
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import androidx.core.app.NotificationCompat
import com.dev.module_zqc_sleep.R
import com.dev.module_zqc_sleep.activity.AlarmStopActivity
import java.io.IOException

class AlarmReceiver : BroadcastReceiver() {
    companion object {
        var mediaPlayer: MediaPlayer? = null
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        if (context == null) return

        showNotification(context)

        val (audioPath, alarmVolume, useVibrator) = getAlarmSetting(context)

        if (useVibrator == true) {
            useVibrator(context)
        }

        if (!audioPath.isNullOrEmpty() && alarmVolume != null) {
            playAudio(context, audioPath, alarmVolume)
        }
    }

    private fun showNotification(context: Context?) {
        val notificationManager = context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        val alarmId = generateUniqueAlarmId(context)
        val intent = Intent(context, AlarmStopActivity::class.java).apply {
            putExtra("alarm_id", alarmId)
        }
        val pendingIntent = PendingIntent.getActivity(
            context,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        // 创建通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel("alarm_channel", "Alarm Channel", NotificationManager.IMPORTANCE_HIGH)
            notificationManager.createNotificationChannel(channel)
        }

        // 创建通知
        val notificationBuilder = NotificationCompat.Builder(context, "alarm_channel")
            .setSmallIcon(R.mipmap.m_alarm_ic4)
            .setContentTitle("闹钟响了")
            .setContentText("起床时间到了！")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_ALARM)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)

        notificationManager.notify(1, notificationBuilder.build())
    }

    private fun playAudio(context: Context, audioPath: String, alarmVolume: Float) {
        mediaPlayer?.release()
        mediaPlayer = MediaPlayer().apply {
            setAudioAttributes(
                AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .build()
            )
            try {
                setVolume(alarmVolume, alarmVolume)
                setDataSource(context, Uri.parse(audioPath))
                prepare()
                start()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        mediaPlayer?.setOnCompletionListener {
            it.start()
        }
    }

    @Suppress("DEPRECATION")
    private fun useVibrator(context: Context?) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            val vibratorManager = context?.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
            val vibrator = vibratorManager.defaultVibrator
            val effect = VibrationEffect.createOneShot(2000, VibrationEffect.DEFAULT_AMPLITUDE)
            vibrator.vibrate(effect)
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val vibrator = context?.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
            val effect = VibrationEffect.createOneShot(2000, VibrationEffect.DEFAULT_AMPLITUDE)
            vibrator.vibrate(effect)
        } else {
            val vibrator = context?.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
            vibrator.vibrate(2000)
        }
    }

    private fun getAlarmSetting(context: Context?): Triple<String?, Float?, Boolean?> {
        val sharedPref = context?.getSharedPreferences("AlarmPreferences", Context.MODE_PRIVATE)
        val audioPath = sharedPref?.getString("audioPath", null)
        val alarmVolume = sharedPref?.getFloat("alarm_volume", 0.1f)
        val useVibrator = sharedPref?.getBoolean("vibrator", false)
        return Triple(audioPath, alarmVolume, useVibrator)
    }

    private fun generateUniqueAlarmId(context: Context): Int {
        val sharedPreferences = context.getSharedPreferences("AlarmPreferences", Context.MODE_PRIVATE)
        val currentId = sharedPreferences.getInt("alarmId", 0)
        val newId = currentId + 1
        sharedPreferences.edit().putInt("alarmId", newId).apply()
        return newId
    }

    /**
     * 设置重复闹钟
     *
     * @param triggerTime 闹钟首次触发的时间 毫秒
     * @param interval 重复间隔的时间长度 毫秒
     */
    fun setRepeatingAlarm(context: Context, triggerTime: Long, interval: Long) {
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent(context, AlarmReceiver::class.java)
        val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)

        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, triggerTime, interval, pendingIntent)
    }

}
